const STORAGE_KEY = "mockProductList";

function getMockProducts() {
  return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
}

function saveMockProducts(products) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(products));
}

export async function fetchProducts() {
  return getMockProducts();
}

export async function createProduct(product) {
  const products = getMockProducts();
  products.push({
    ...product,
    productId: Date.now(),
    status: "下架",
    clickCount: 0,
  });
  saveMockProducts(products);
}

export async function updateProduct(id, product) {
  const products = getMockProducts();
  const updated = products.map((p) =>
    p.productId == id ? { ...p, ...product } : p
  );
  saveMockProducts(updated);
}

export async function deleteProduct(id) {
  const products = getMockProducts().filter((p) => p.productId != id);
  saveMockProducts(products);
}

export async function toggleProductStatus(id) {
  const products = getMockProducts().map((p) =>
    p.productId == id
      ? { ...p, status: p.status === "上架" ? "下架" : "上架" }
      : p
  );
  saveMockProducts(products);
}

export async function incrementClickCount(id) {
  const products = getMockProducts().map((p) =>
    p.productId == id ? { ...p, clickCount: p.clickCount + 1 } : p
  );
  saveMockProducts(products);
}
